package com.parse.dxf.utils;

import com.parse.dxf.entity.VertexInfo;

import java.util.List;

public class MathUtils {

    /**
     * 判断点是否在多边形内
     * @param x
     * @param y
     * @param polygon
     * @return
     */
    public static boolean isPointInPolygon(double x, double y, List<VertexInfo> polygon) {
        boolean isInside = false;
        int count = polygon.size();
        for (int i = 0, j = count - 1; i < count; j = i++) {
            VertexInfo start = polygon.get(i);
            VertexInfo end = polygon.get(j);
            if (((start.getY() > y) != (end.getY() > y)) &&
                    (x < (end.getX() - start.getX()) * (y - start.getY()) / (end.getY() - start.getY()) + start.getX())) {
                isInside = !isInside;
            }
        }
        return isInside;
    }


    /**
     * 计算多边形面积
     * @param polygon 多边形的顶点列表
     * @return 多边形的面积
     */
    public static double calculatePolygonArea(List<VertexInfo> polygon) {
        int count = polygon.size();
        if (count < 3) {
            return 0; // Not a polygon
        }

        double area = 0;
        for (int i = 0; i < count; i++) {
            VertexInfo current = polygon.get(i);
            VertexInfo next = polygon.get((i + 1) % count);
            area += current.getX() * next.getY();
            area -= current.getY() * next.getX();
        }
        area = Math.abs(area) / 2.0;
        return area;
    }
}
